package com.mystnihon.actions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import ca.benow.transmission.model.TorrentStatus;
import ca.benow.transmission.model.TorrentStatus.TorrentField;

import com.mystnihon.models.Seedbox;
import com.mystnihon.models.SeedboxManager;
import com.opensymphony.xwork2.ActionSupport;

public class SeedboxsAction extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private int seedbox;

	private SeedboxManager manager = new SeedboxManager();
	private Map<String, Object> session;

	public String selectSeedbox() {

		System.out.println("select seedbox" + seedbox);

		// return "success";

		if (seedbox < manager.getSeedboxList().size()) {
			getSession().put("selectedSeedbox",
					manager.getSeedboxList().get(seedbox));
			return ActionSupport.SUCCESS;
		} else {
			this.addActionError("Invalid seedbox");
			return ActionSupport.ERROR;
		}

	}

	@Override
	public void setSession(Map<String, Object> obj) {
		this.session = obj;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public Seedbox getSelectedSeedbox() {
		if (session != null) {
			if (session.get("selectedSeedbox") != null) {
				System.out.println("Return un objet de session");
				return (Seedbox) session.get("selectedSeedbox");
			}
		}
		System.out.println("return null");
		return null;
	}

	public ArrayList<Seedbox> getSeedboxsList() {
		return manager.getSeedboxList();
	}

	public List<TorrentStatus> getTorrentList() {
		System.out.println("List torrents.");

		Seedbox seedbox = getSelectedSeedbox();
		System.out.println("Get seedbox : " + seedbox.getName() + ".");
		if (seedbox != null) {
			try {
				if (seedbox.connect()) {
					return seedbox.getAllTorrents(myfields);
				} else {
					System.err.println("Couldn't connect.");
					return null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.err.println("Couldn't retrieve seedbox object from session.");
		return null;

	}

	public String listSeedboxs() {
		System.out.println("list");
		return ActionSupport.SUCCESS;
	}

	public int getSeedbox() {
		return seedbox;
	}

	public void setSeedbox(int seedbox) {
		this.seedbox = seedbox;
	}

	/**
	 * Requested fields
	 * 
	 */
	private TorrentField[] myfields = new TorrentField[] { TorrentField.id,
			TorrentField.name, TorrentField.status, TorrentField.percentDone,
			TorrentField.addedDate, TorrentField.startDate,
			TorrentField.doneDate, TorrentField.totalSize,
			TorrentField.isFinished, TorrentField.magnetLink,
			TorrentField.sizeWhenDone, TorrentField.files,
			TorrentField.fileStats };
}
